<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\Exception;
use think\exception\ValidateException;

use service\PayService;

use think\facade\Db;
use service\JsonService as Json;
use app\admin\controller\BaseController;

use app\common\model\User;
use app\common\model\Product;
use app\common\model\ProductOrder;
use app\common\model\UserSection;
use app\common\model\UserCompany;
use app\common\model\UserSectionLevel;

class ProductController extends BaseController
{
    /**
     * 供应商产品状态
     */
    public function isRenew()
    {
        return Json::success('ok', ProductOrder::isRenew($this->user_id));
    }

    /**
     * 续费-确认订单
     */
    public function getProductOrderInfo()
    {
        $userInfo = User::getFind(['id' => $this->user_id]);

        $orderInfo = Productorder::where([
                ['section_id', '=', $userInfo['section_id']],
                ['pid', '=', 0],
                ['status', '>', 1],
                ['is_installment', '>', 0],
                ['finish_time', '=', 0],
            ])
            ->limit(1)
            ->order('pay_time DESC')
            ->find();

        $productInfo = $orderInfo['product_info'];

        $levelInfo = UserSectionLevel::getFind(['id' => $userInfo['section_level_id']]);

        if($levelInfo && $levelInfo['level'] == 1){
            $productInfo['level'] = 1;
        }else{
            $productInfo['level'] = 0;
        }

        $companyId = UserSection::getVal(['id' => $orderInfo['section_id']], 'company_id');
        $productInfo['company_name'] = UserCompany::getVal(['id' => $companyId], 'name');
        
        return Json::success('ok', $productInfo);
    }

    /**
     * 续费-下单支付
     */
    public function setPay()
    {
        $userInfo = User::getFind(['id' => $this->user_id]);

        $orderInfo = Productorder::where([
                ['section_id', '=', $userInfo['section_id']],
                ['pid', '=', 0],
                ['status', '>', 1],
                ['finish_time', '=', 0],
            ])
            ->limit(1)
            ->order('pay_time DESC')
            ->find();

        if(!$orderInfo) return Json::fail('订单状态异常，请联系管理员！');

        /** 订单号 */
        $orderNo = getOrderNo();

        $data = [
            'pid'                  => $orderInfo['id'],
            'order_no'             => $orderNo,
            'user_id'              => $this->user_id,
            'section_id'           => $orderInfo['section_id'],
            'product_id'           => $orderInfo['product_id'],
            'price'                => $orderInfo['installment_price'],
            'num'                  => 1,
            'installment_price'    => $orderInfo['installment_price'],
            'installment_nums'     => 0,
            'installment_nums_all' => 0,
            'is_installment'       => $orderInfo['is_installment'],
            'product_info'         => json_encode($orderInfo['product_info']),
            'pay_type'             => 1,
            'invoice'              => $orderInfo['invoice'],
        ];

        $flag = ProductOrder::add($data);
        if(!$flag) return Json::fail('下单失败，请稍后重试!');

        $order = [
            'out_trade_no' => $orderNo,
            'description' => '购买套餐',
            'amount' => [
                 'total'    => $orderInfo['installment_price'] * 100,
            ],
        ];

        $result = PayService::createRenewProductOrder($order);

        if($result['code_url']){
            return Json::success('ok', [
                'code_url' => $result['code_url'],
                'order_no' => $orderNo,
            ]);
        }

        return Json::fail($result->message);
    }

    /**
     * 续费-支付回调
     */
    public function notify_renew()
    {
        PayService::notifyRenew();
    }



    /**
     * 下单支付
     */
    public function payCodeProduct()
    {
        $productId = Request()->param('product_id', 0);
        $num       = Request()->param('num', 1);

        /** 产品信息 */
        $productInfo = Product::getFind(['id' => $productId]);
        if(!$productInfo) return Json::fail('产品不存在');

        /** 用户信息 */
        $userInfo = User::getFind(['id' => $this->user_id], 'section_id, openid');

        /** 订单号 */
        $orderNo = getOrderNo();

        if($productInfo['is_installment']){
            $price = $productInfo['down_payment'];
        }else{
            $price = $productInfo['total'];
        }

        $data = [
            'order_no'             => $orderNo,
            'user_id'              => $this->user_id,
            'section_id'           => $userInfo['section_id'],
            'product_id'           => $productId,
            'price'                => $price,
            'num'                  => $num,
            'installment_price'    => $productInfo['installment_price'],
            'installment_nums'     => $productInfo['is_installment'] ? 1 : 0,
            'installment_nums_all' => $productInfo['installment_nums'],
            'is_installment'       => $productInfo['is_installment'],
            'product_info'         => json_encode($productInfo),
            'pay_type'             => 1,
            'invoice'              => $productInfo['invoice'],
        ];
        
        $flag = ProductOrder::add($data);
        if(!$flag) return Json::fail('下单失败，请稍后重试!');

        $order = [
            'out_trade_no' => $orderNo,
            'description' => '购买套餐',
            'amount' => [
                //  'total'    => $price * 100,
                 'total'    => 1,
            ],
        ];

        $result = PayService::createCodeProductOrder($order);

        if($result['code_url']){
            return Json::success('ok', [
                'code_url' => $result['code_url'],
                'order_no' => $orderNo,
            ]);
        }

        return Json::fail($result->message);
    }

    /**
     * 支付回调
     */
    public function notify_code()
    {
        PayService::notifyCode();
    }

    /**
     * 是否支付
     */
    public function isPay()
    {
        $isPay = ProductOrder::isPay(Request()->param('order_no', '')) ? 1 : 0;
        return Json::success('ok', ['is_pay' => $isPay]);  
    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        $orderNo = Request()->param('order_no', '');

        $flag = ProductOrder::editWhere(['status' => 4], ['order_no' => $orderNo]);
        if(!$flag) return Json::fail();
        return Json::success();
    }

    /**
     * 缴费记录
     */
    public function getProductOrderList()
    {
        $page = Request()->param('page', 1);

        $list = ProductOrder::getList(['user_id' => $this->user_id], 1, $page, 20, '*', 'id DESC');

        if(!$list) return Json::fail('暂无数据');

        foreach($list as &$info){
            $info['pay_time']    = $info['pay_time'] ? date('Y-m-d H:i:s', $info['pay_time']) : '';
            $info['finish_time'] = $info['finish_time'] ? date('Y-m-d H:i:s', $info['finish_time']) : '';
        }

        return Json::success('ok', $list, ProductOrder::getNum(['user_id' => $this->user_id]));
    }
}